package com.justreading.nio.zerocopy;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author LYJ
 * @Description
 * @date 2021 年 10 月 07 日 18:26
 */
public class NewIOServer {

    public static void main(String[] args)  {
        SocketChannel channel = null;
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.socket().bind(new InetSocketAddress(6668));
            ByteBuffer byteBuffer = ByteBuffer.allocate(4096);
            while (true){
                channel = serverSocketChannel.accept();
                int read;
                while ((read = channel.read(byteBuffer)) != -1){
                    byteBuffer.rewind();
                }
            }
        } catch (IOException e) {
            if(channel != null){
                try {
                    System.out.println(channel.getRemoteAddress().toString() + "关闭连接");
                    channel.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
